package cn.highedu.mvc;

import cn.highedu.entity.User;
import cn.highedu.http.HttpServletRequest;
import cn.highedu.http.HttpServletResponse;

import java.io.*;
import java.time.LocalDate;
import java.util.Map;

/**
 * 用户控制器，封装用户业务逻辑
 */
@Controller
public class UserController {
    /**
     * 封装注册逻辑
     * @param request 代表HTTP请求信息
     * @param response 代表HTTP响应信息
     * @param model 代表在视图上显示的数据
     * @return 返回一个视图文件名称
     */
    @RequestMapping("/register")
    public String register(HttpServletRequest request,
                           HttpServletResponse response,
                           Map<String, Object> model) throws IOException {
        String store = "users.dat";
        String name = request.getParameter("name");
        String gender = request.getParameter("gender");
        String date = LocalDate.now().toString();
        //注册逻辑，保存用户信息
        System.out.println("正在注册用户："+name);
        User user = new User(name, gender, "123", LocalDate.now());
        ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(store));
        out.writeObject(user);
        out.close();
        //在界面显示信息
        model.put("name", name);
        model.put("gender", gender);
        model.put("date", date);
        model.put("message", "欢迎"+name+"注册到当前系统");
        return "register_result.html"; //视图文件名称
    }

    @RequestMapping("/users")
    public String users(HttpServletRequest request,
                        HttpServletResponse response,
                        Map<String, Object> model) throws Exception{
        //获取用户信息
        String store = "users.dat";
        ObjectInputStream in = new ObjectInputStream(new FileInputStream(store));
        User user = (User) in.readObject();
        in.close();
        //String s = null;
        //s.length();
        model.put("name", user.getName());
        model.put("gender", user.getGender());
        return "users.html";
    }

}
